package com.zx.framework.web.property;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class ManyCustomDateEditor extends PropertyEditorSupport {
	private static final Logger LOGGER = Logger
			.getLogger(ManyCustomDateEditor.class);
	/**
	 * 是否允许为空
	 */
	private final boolean allowEmpty;
	
	private static Pattern patternFull = Pattern.compile("[\\d]{4}-[\\d]{2}-[\\d]{2}\\s[\\d]{2}:[\\d]{2}:[\\d]{2}");
	
	private static Pattern patternYyyymmdd = Pattern.compile("[\\d]{4}-[\\d]{2}-[\\d]{2}");
	
	private static Pattern patternHhmmss = Pattern.compile("[\\d]{2}:[\\d]{2}:[\\d]{2}");
	
	private static DateFormat formatFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static DateFormat formatYyyymmdd = new SimpleDateFormat("yyyy-MM-dd");
	
	private static DateFormat formatHHmmss = new SimpleDateFormat("HH:mm:ss");
	
	public ManyCustomDateEditor(boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		try {
			return formatFull.format(value);
		} catch (Exception e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，尝试下一格式！", e);
			}
		}
		try {
			return formatYyyymmdd.format(value);
		} catch (Exception e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，尝试下一格式！", e);
			}
		}
		
		try {
			return formatHHmmss.format(value);
		} catch (Exception e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，格式不正确！", e);
			}
		}
		return "";
	}

	@Override
	public void setAsText(String source) throws IllegalArgumentException {
		Matcher matcher = null;
		try {
			matcher = patternFull.matcher(source);
			if(matcher.matches()){
				setValue(formatFull.parse(source));
				return;
			}
		} catch (ParseException e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，尝试下一格式！", e);
			}
		}
		try {
			matcher = patternYyyymmdd.matcher(source);
			if(matcher.matches()){
				setValue( formatYyyymmdd.parse(source));
				return;
			}
		} catch (ParseException e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，尝试下一格式！", e);
			}
		}
		
		try {
			matcher = patternHhmmss.matcher(source);
			if(matcher.matches()){
				setValue( formatHHmmss.parse(source));
				return;
			}
		} catch (ParseException e) {
			if(LOGGER.isDebugEnabled()){
				LOGGER.debug("转换格式失败，格式不正确！", e);
			}
		}
		if(allowEmpty){
			setValue(null);
		}
	}
}
